package com.autonavi.yunda.yunji.controller;

import com.autonavi.yunda.yunji.common.enums.EditType;
import com.autonavi.yunda.yunji.core.service.CodeGenerateService;
import com.autonavi.yunda.yunji.core.service.InterfaceConfigService;
import com.autonavi.yunda.yunji.core.service.TaskConfigService;
import com.autonavi.yunda.yunji.core.vo.node.BaseNode;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * function节点参数列表-json字符串-groovy代码相互转换
 */
@RestController
@RequestMapping("/function/change")
public class CodeGenerateController {

    @Resource
    private CodeGenerateService codeGenerateService;
    @Resource
    private InterfaceConfigService interfaceConfigService;
    @Resource
    private TaskConfigService taskConfigService;


    /**
     * 生成代码
     * 通过页面传入的参数列表转换成groovy代码并返回
     *
     * @param request 参数列表
     * @return groovy代码
     */
    @PostMapping(value = "toCode", produces = "application/json;charset=UTF-8")
    public String generateCode(@RequestBody JsonNode request) throws Exception {
        BaseNode baseNode = BaseNode.parseNode(request);
        JsonNode editType = request.get("editType");
        String projectId;
        if (editType == null || editType.asText().equalsIgnoreCase(EditType.INTERFACE.name())) {
            JsonNode interfaceId = request.get("interfaceId");
            projectId = interfaceId != null ? interfaceConfigService.findByIdOrThrow(interfaceId.asLong()).getProjectId() : null;
        } else {
            JsonNode interfaceId = request.get("interfaceId");
            projectId = interfaceId != null ? taskConfigService.findByIdOrThrow(interfaceId.asLong()).getProjectId() : null;
        }
        return codeGenerateService.generateCode(baseNode, projectId);
    }


}
